package com.huiyujinrong.qiangdanbao.activity.my;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huiyujinrong.qiangdanbao.R;
import com.huiyujinrong.qiangdanbao.permission.PermissionSupport;
import com.huiyujinrong.qiangdanbao.utils.SharedHelper;
import com.huiyujinrong.qiangdanbao.utils.TakePhotoView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * 意见反馈
 */

public class FeedbackActivity extends PermissionSupport implements FeedbackContract.View {


    @BindView(R.id.toolbar_Title)
    TextView toolbar_title;
    @BindView(R.id.toolbar_Back)
    RelativeLayout back;

    @BindView(R.id.fb_image1)
    TakePhotoView image1;
    @BindView(R.id.fb_no1)
    ImageView no1;

    @BindView(R.id.fb_image2)
    TakePhotoView image2;
    @BindView(R.id.fb_no2)
    ImageView no2;

    @BindView(R.id.fb_image3)
    TakePhotoView image3;
    @BindView(R.id.fb_no3)
    ImageView no3;

    @BindView(R.id.fb_image4)
    TakePhotoView image4;
    @BindView(R.id.fb_no4)
    ImageView no4;

    @BindView(R.id.fb_content)
    EditText content;

    private ProgressDialog progressDialog;

    //获取图片
    private String outputPath;

    private int photo;  //相册选择

    private FeedbackPresenter presenter;

    private Toast t;

    private File file1 = null;
    private File file2 = null;
    private File file3 = null;
    private File file4 = null;
    private boolean is2Setting;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        ButterKnife.bind(this);

        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);

        setToolbar();

        setLongClick();

        presenter = new FeedbackPresenter(this);
        presenter.start();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (is2Setting) {
            is2Setting = false;
            requestPermissions();
        }
    }


    /**
     * 选择 上传身份证照片
     * 相机  or  手机相册
     */
    private void getImages() {
        final String items[] = {"相机", "从手机相册选择"};
        new AlertDialog.Builder(this)
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                //照相
                                callSysCamera();
                                break;
                            case 1:
                                //相册
                                callSysAlbum();
                                break;
                            default:
                        }
                    }
                }).show();
    }

    //打开相机
    private void callSysCamera() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
        startActivityForResult(intent, 0);
    }


    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String path = images.get(0).path;
                getPDialog();
                getLuBan(new File(path));
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }


    private void getPDialog() {
        progressDialog.setMessage("正在加载图片...");
        progressDialog.show();
    }


    private void getLuBan(File imageFile) {
        Luban.with(this)
                .load(imageFile)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        progressDialog.dismiss();
                        switch (photo) {
                            case 1:
                                Bitmap bt1 = getBitmap4File(image1, file);
                                file1 = file;
                                image1.setBackground(new BitmapDrawable(bt1));
                                image1.setImageBitmap(null);
                                break;
                            case 2:
                                Bitmap bt2 = getBitmap4File(image2, file);
                                file2 = file;
                                image2.setBackground(new BitmapDrawable(bt2));
                                image2.setImageBitmap(null);
                                break;
                            case 3:
                                Bitmap bt3 = getBitmap4File(image3, file);
                                file3 = file;
                                image3.setBackground(new BitmapDrawable(bt3));
                                image3.setImageBitmap(null);
                                break;
                            case 4:
                                Bitmap bt4 = getBitmap4File(image4, file);
                                file4 = file;
                                image4.setBackground(new BitmapDrawable(bt4));
                                image4.setImageBitmap(null);
                                break;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过去出现问题时调用
                        progressDialog.dismiss();
                    }
                }).launch();//启动压缩
    }

    //获取本地文件中的Bitmap图像源
    private Bitmap getBitmap4File(ImageView imageView, File imageFile) {
        int imageViewWidth = imageView.getWidth();
        int imageViewHeight = imageView.getHeight();
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //设置这个，只得到Bitmap的属性信息放入opts，而不把Bitmap加载到内存中
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imageFile.getPath(), opts);
        int bitmapWidth = opts.outWidth;
        int bitmapHeight = opts.outHeight;
        int scale = Math.min(imageViewWidth / bitmapWidth, imageViewHeight / bitmapHeight);
        opts.inSampleSize = scale;
        //内存不足时可被回收
        opts.inPurgeable = true;
        opts.inJustDecodeBounds = false;

        Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getPath(), opts);
        return bitmap;
    }


    //打开相册
    private void callSysAlbum() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, 1);
    }

    /**
     * 长按图片  显示删除图片 按钮
     */
    private void setLongClick() {
        image1.setLongClickListener(new TakePhotoView.OnLongTakePhotoClickListener() {
            @Override
            public void onLongClick() {
                no1.setVisibility(View.VISIBLE);
            }
        });
        image2.setLongClickListener(new TakePhotoView.OnLongTakePhotoClickListener() {
            @Override
            public void onLongClick() {
                no2.setVisibility(View.VISIBLE);
            }
        });
        image3.setLongClickListener(new TakePhotoView.OnLongTakePhotoClickListener() {
            @Override
            public void onLongClick() {
                no3.setVisibility(View.VISIBLE);
            }
        });
        image4.setLongClickListener(new TakePhotoView.OnLongTakePhotoClickListener() {
            @Override
            public void onLongClick() {
                no4.setVisibility(View.VISIBLE);
            }
        });
        //////////////////////////////////////////////////////////
        image1.setShortClickListener(new TakePhotoView.OnTakePhotoClickListener() {
            @Override
            public void onClick() {

                photo = 1;
                requestPermissions();
            }
        });
        image2.setShortClickListener(new TakePhotoView.OnTakePhotoClickListener() {
            @Override
            public void onClick() {

                photo = 2;
                requestPermissions();

            }
        });
        image3.setShortClickListener(new TakePhotoView.OnTakePhotoClickListener() {
            @Override
            public void onClick() {

                photo = 3;
                requestPermissions();
            }
        });
        image4.setShortClickListener(new TakePhotoView.OnTakePhotoClickListener() {
            @Override
            public void onClick() {
                photo = 4;
                requestPermissions();

            }
        });

    }

    private void requestPermissions() {
        doRequestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 8, listener);
    }

    PermissionListener listener = new PermissionListener() {
        @Override
        public void onPermissionsGranted(int requestCode) {
            getImages();
        }

        @Override
        public void onPermissionsDenied(int requestCode) {
            showTipsDialog();
        }
    };

    //显示所有提示对话框
    private void showTipsDialog() {
        new android.app.AlertDialog.Builder(this)
                .setTitle("授权提示：")
                .setMessage("应用缺少必要权限,无法使用部分功能。是否去设置?")
                .setNegativeButton("不设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        finish();
                    }
                })
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        is2Setting = true;
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }
                }).show();
    }

    /**
     * 设置toolbar
     */
    private void setToolbar() {
        toolbar_title.setText("意见反馈");
        back.setVisibility(View.VISIBLE);
    }

    @OnClick(R.id.toolbar_Back)
    void goBack() {
        finish();
    }

    /**
     * 点击  小红圈XX  删除已照图片
     *
     * @param view
     */
    @OnClick({R.id.fb_no1, R.id.fb_no2, R.id.fb_no3, R.id.fb_no4})
    void onClickes(View view) {
        switch (view.getId()) {
            case R.id.fb_no1:
                file1 = null;
                no1.setVisibility(View.GONE);
                image1.setBackgroundResource(R.drawable.img_yj_tj);
                break;
            case R.id.fb_no2:
                file2 = null;
                no2.setVisibility(View.GONE);
                image2.setBackgroundResource(R.drawable.img_yj_tj);
                break;
            case R.id.fb_no3:
                file3 = null;
                no3.setVisibility(View.GONE);
                image3.setBackgroundResource(R.drawable.img_yj_tj);
                break;
            case R.id.fb_no4:
                file4 = null;
                no4.setVisibility(View.GONE);
                image4.setBackgroundResource(R.drawable.img_yj_tj);
                break;
        }
    }


    /**
     * 提交反馈
     */
    @OnClick(R.id.fb_upload)
    void upLoadFeedback() {
        if (!TextUtils.isEmpty(content.getText().toString())) {
            presenter.upLoadFeedback(String.valueOf(SharedHelper.get(this, "user_id", "")), content.getText().toString(), file1, file2, file3, file4);
        } else {
            showToast("请填写反馈内容");
        }
    }


    @Override
    public void showToast(String str) {
        if (t == null) {
            t = Toast.makeText(this, str, Toast.LENGTH_SHORT);
        } else {
            t.setText(str);
            t.setDuration(Toast.LENGTH_SHORT);
        }
        t.show();
    }

    @Override
    public void inOK() {
        finish();
    }

    @Override
    public void disPlay() {
        progressDialog.setMessage("提交反馈中...");
        progressDialog.show();
    }

    @Override
    public void disMiss() {
        progressDialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.end();
    }
}
